package ming.controller.socket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws") //此注解相当于设置访问URL
public class MachineWebSocket2 {


    private String machineId;
    protected Session session;

    private static ConcurrentHashMap<String,MachineWebSocket> webSocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        try {
//            if (StringUtils.isEmpty(machineNo)){
//                throw new JeecgBootException("缺少参数");
//            }
//            this.session = session;
//            session.setMaxIdleTimeout(60000*3);//3分钟生命周期
//            log.info("【设备连接消息】有新的设备上线bindToken：，"+machineNo);
//            this.machineId = machineNo;
//            if (webSocketMap.containsKey(this.machineId)){
//                CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,this.machineId+"重连，关闭以前的连接！");
//                webSocketMap.get(this.machineId).session.close(closeReason);
//                webSocketMap.remove(this.machineId);
//                log.info("【设备连接消息（"+session.getId()+"）】重连，关闭以前的连接，"+machineId.trim());
//            }else{
//                webSocketMap.put(this.machineId,this);
//            }
        } catch (Exception e) {
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError( Session session, Throwable error){
    }


    @OnClose
    public void onClose() {
        try {
            webSocketMap.remove(this.machineId);
        } catch (Exception e) {
        }
    }

    /**
     * 接受消息  设备心跳缓存
     * @param message
     */
    @OnMessage
    public void onMessage(String message,Session session) {
        try{
            System.out.println(message);
            session.getAsyncRemote().sendText("test");
        }catch (Exception e){
        }
    }

}
